{% extends 'web/layout/manage.html' %}
{% load static %}
{% block title %}Issues{% endblock title %}

{% block css %}
    <link rel="stylesheet" href="{% static 'plugins/editor-md/css/editormd.min.css' %}">
    <link rel="stylesheet" href="{% static 'plugins/editor-md/css/editormd.preview.min.css' %}">
    <link rel="stylesheet" href="{% static 'plugins/dist/css/bootstrap-datepicker.min.css' %}">
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-select/css/bootstrap-select.min.css' %}">
<style>


    .comment-area {
        margin-left:10px;
        margin-right:10px;
        margin-bottom:10px;
    }
    .comment-area .item {
            margin-top: 20px;
        }

    .comment-area .left-avatar {
        float: left;
        margin-right: 10px;
        display: inline-block;
        width: 30px;
        height: 30px;
        background-color: #304659;
        color: white;
        text-align: center;
        line-height: 30px;
        border-radius: 50%;
    }

    .comment-area .right-info {
        padding-left: 35px;
    }

    .comment-area .right-info .desc .msg {
        display: inline-block;
        padding-right: 20px;
        color: #8c8c8c;
    }

    .comment-area .child {
        padding-left: 55px;
    }

    .comment-area .error-msg {
        color: red;
    }

    .comment-area .reply-user {
        display: inline-block;
        background-color: #ddd;
        color: black;
        padding: 6px 8px;
        margin-left: 20px;
        border-radius: 8px;
        cursor: pointer;
    }    


    .panel-default{
        margin-top:10px;
    }
    .panel-default .panel-heading {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
        }
    .panel-body{
        padding:0px;
    }
    .title_list{
        border-right:1px solid #dddddd;
    }
    .content{
        border-left:1px solid #dddddd;
        margin-left: -1px;
    }
    .editormd-fullscreen{
            z-index: 1001;
        }

    .editormd{
            margin-bottom: 10px;
        }
    .error-msg {
        color: red;
        position: absolute;     
        font-size: 12px; 
    }

    .others {
        margin-bottom:0px;
    }
    .form-horizontal{
        margin-top:10px;
        margin-right:10px;
    }
</style>
{% endblock css %}
{% block content %}

<!-- panel -->
<div class="container-fluid bs-example" >    <!-- container-fluid -->
    <!-- 左侧面板: 问题编辑 -->
    <div class="col-sm-7">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">编辑问题</h3>
            </div>
            <div class="panel-body">
                <form id="issueForm" class="form-horizontal"method="POST" >
                    {% csrf_token %}
                    <div class="form-group">
                        <label for="{{ form.issues_type.id_for_label}}" class="col-md-2 control-label">{{form.issues_type.label}}</label>
                        <div class="col-md-10">
                            <div>{{form.issues_type}}</div>
                            <div class="error-msg"></div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="{{ form.subject.id_for_label}}" class="col-md-2 control-label">{{form.subject.label}}</label>
                        <div class="col-md-10">
                            <div>
                                {{form.subject}}
                            </div>
                            <div class="error-msg"></div>
                        </div>
                                            
                    </div>

                    <div class="form-group">
                        <label for="{{ form.module.id_for_label}}" class="col-md-2 control-label">{{form.module.label}}</label>
                        <div class="col-md-10">
                            <div>{{form.module}}</div>
                            <div class="error-msg"></div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="{{ form.desc.id_for_label}}" class="col-md-2 control-label">{{form.desc.label}}</label>
                        <div class="col-md-10">
                                                
                            <div id='id_editor'>{{form.desc}}</div>
                            <div class="error-msg"></div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="{{ form.status.id_for_label}}" class="col-md-2 control-label">{{form.status.label}}</label>
                        <div class="col-md-4">
                            <div>{{form.status}}</div>
                            <div class="error-msg"></div>
                        </div>
                        <label for="{{ form.priority.id_for_label}}" class="col-md-2 control-label">{{form.priority.label}}</label>
                        <div class="col-md-4">
                            <div>{{form.priority}}</div>
                            <div class="error-msg"></div>
                        </div>
                    </div>
    
                    <div class="form-group">
                        <label for="{{ form.assign.id_for_label}}" class="col-md-2 control-label">{{form.assign.label}}</label>
                        <div class="col-md-4">
                            {{form.assign}}
                            <div class="error-msg"></div>
                        </div>
                        <label for="{{ form.attention.id_for_label}}" class="col-md-2 control-label">{{form.attention.label}}</label>
                        <div class="col-md-4">
                            {{form.attention}}
                            <div class="error-msg"></div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="{{ form.start_date.id_for_label}}" class="col-md-2 control-label">{{form.start_date.label}}</label>
                        <div class="col-md-4">
                            <div>{{form.start_date}}</div>
                            <div class="error-msg"></div>
                        </div>
                        <label for="{{ form.end_date.id_for_label}}" class="col-md-2 control-label">{{form.end_date.label}}</label>
                        <div class="col-md-4">
                            <div>{{form.end_date}}</div>
                            <div class="error-msg"></div>
                        </div>
                    </div>


                    <div class="form-group">
                        <label for="{{ form.mode.id_for_label}}" class="col-md-2 control-label">{{form.mode.label}}</label>
                        <div class="col-md-4">
                            <div>{{form.mode}}</div>
                            <div class="error-msg"></div>
                        </div>
                        <label for="{{ form.parent.id_for_label}}" class="col-md-2 control-label">{{form.parent.label}}</label>
                        <div class="col-md-4">
                            {{form.parent}}
                            <div class="error-msg"></div>
                        </div>
                    </div>
                                                                    
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default btn-xs" data-dismiss="modal">关 闭</button>
                <button id="btnFormSubmit" type="button" class="btn btn-primary btn-xs" onclick = "submitForm();">提 交</button>
            </div>

        </div>
    </div>
    <!-- 右侧面板: 回复和评论 -->
    <div class="col-sm-5">
         <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">修改记录</h3>
            </div>
            <div class="panel-body comment-area">

                <div class="comment-list">

                </div>

                <hr/>
                <div class="comment-text" id="commentText">

                    <div class="form-group">
                        <textarea id="content" rows="5" class="form-control"
                                    placeholder="请输入要回复的内容"></textarea>
                        <span class="error-msg"></span>
                    </div>

                    <input class="btn btn-primary" type="button" id="btnSubmit" value="提 交">

                    <div class="reply-user hide" id="replyUser">
                        回复 <span></span>
                        <i class="fa fa-times-circle" aria-hidden="true" style="color: #9d9d9d;"></i>
                    </div>
                </div>



            </div>
            
        </div>

   </div>
</div>

    <!-- 隐藏：回复和评论的模板 -->
<div class="hide" id="recordTemplate">
    <div class="item clearfix">
        <div class="left-avatar"></div>
        <div class="right-info">
            <pre></pre>
            <div class="desc">
                <div class="msg">
                    <i class="fa fa-bullhorn" aria-hidden="true"></i>
                    <span class="type"></span>
                </div>
                <div class="msg">
                    <i class="fa fa-user-o" aria-hidden="true"></i>
                    <span class="user"></span>
                </div>
                <div class="msg">
                    <i class="fa fa-clock-o" aria-hidden="true"></i>
                    <span class="date"></span>
                </div>

                <a href="#commentText" class="reply">
                    <i class="fa fa-commenting-o" aria-hidden="true"></i> 回复
                </a>

            </div>
        </div>
        <div class="child">

        </div>
    </div>
</div>


{% endblock content %}
{% block js %}
    <script src="{% static 'plugins/editor-md/editormd.min.js' %}"></script>
    <script src="{% static 'plugins/dist/js/bootstrap-datepicker.min.js' %}"></script>
    <script src="{% static 'plugins/dist/locales/bootstrap-datepicker.zh-CN.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-select/js/bootstrap-select.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-select/js/i18n/defaults-zh_CN.min.js' %}"></script>
    <script>
        var EDITORMD;
        $(function () {
                $('.error-msg').empty();
                initEditorMd();
                //bindBootStrapShownEvent();
                initDatePicker();
                initIssuesRecord();
                bindReply();
                bindCancelReplyUser();
                bindClickSubmitBtn();
                bindIssueChange();

            });

        /*
        回复问题
         */
        function bindReply() {
            $('.comment-list').on('click', '.reply', function () {
                var $item = $(this).parent().parent().parent();
                var id = $item.attr('id');
                var username = $item.attr('username');
                $('#replyUser').removeClass('hide').attr('parent-id', id).children('span').text(username);
            })
        }

        /*
        取消回复
         */
        function bindCancelReplyUser() {

            $('#replyUser').click(function () {
                $(this).addClass('hide').removeAttr('parent-id').children('span').text("");
            })
        } 
        
        /*
        添加对话框：初始化时间选择
         */
        function initDatePicker() {
            $('#id_start_date,#id_end_date').datepicker({
                format: 'yyyy-mm-dd',
                startDate: '0',
                language: "zh-CN",
                autoclose: true
            });
        }

        


        function initEditorMd(){
            if ($('#id_editor').length > 0) {
                EDITORMD = editormd("id_editor", {
                    height:200,
                    //height:"100%",
                    placeholder:"请输入内容",
                    path:"{% static 'plugins/editor-md/lib/' %}",
                    imageUpload:true,				//使能图片上传
                    imageFormats:["jpg",'jpeg','png','gif'],		//图片格式
                    imageUploadURL: "{% url 'web:wiki_upload' project_id=request.tracer.project.id %}", //图片上传地址
                    //markdown对话框会上移，不要固定在窗口
                    toolbarAutoFixed: false,
                    //加载markdown时，以预览的形式显示
                    onload: function () {
                        this.previewing();
                    },
                    //定制markdown的图标，新增加save按钮
                    toolbarIcons: function () {
                    return ["bold", "hr", "del", "italic", "quote", "|", "image", "preview", "watch", "fullscreen", "||", "save"]
                    },
                    //定制save按钮的样式，和onclick ajax函数
                    toolbarCustomIcons: {
                        save: "<input type='button' value='保 存' class='btn btn-success btn-sm' onclick='saveDesc();' />"
                    },
                });
            }
        }

        function saveDesc() {
            //alert('666');
            var postDict = {name: 'desc', value: EDITORMD.getValue()};
            console.log(postDict);
            submitIssueChange(postDict);
            //postAjaxData(postDict);
        }

        function postAjaxData(postDict) {
            $('#id_' + postDict.name).parent().next('.error-msg').text("");

            $.ajax({
                url: "{% url 'web:issue_detail' project_id=request.tracer.project.id issue_id=issue_object.id %}",
                type: "POST",
                header: {
                    "Content-Type": "application/json;charset=utf-8"
                },
                data: JSON.stringify(postDict),
                dataType: "JSON",
                success: function (res) {
                    if (res.status) {
                        createRecordNode(res.data);
                    } else {
                        $('#id_' + postDict.name).parent().next('.error-msg').text(res.error);
                    }
                }
            })
        }


/*
        问题评论的初始化
         */
        function initIssuesRecord() {

            $.ajax({
                url: "{% url 'web:issues_record' project_id=request.tracer.project.id issue_id=issue_object.id %}",
                type: "GET",
                dataType: 'JSON',
                success: function (res) {
                    if (res.status) {
                        $.each(res.data, function (index, item) {
                            createRecordNode(item);
                        })
                    } else {

                    }
                }
            })

        }

        /*
        创建操作记录节点
         */
        function createRecordNode(nodeDict) {
            var $item = $("#recordTemplate").find('.item').clone();
            $item.find('.left-avatar').html(nodeDict.creator[0].toUpperCase());
            $item.find('pre').html(nodeDict.content);
            $item.find('.user').html(nodeDict.creator);
            $item.find('.type').html(nodeDict.reply_type_text);
            $item.find('.date').html(nodeDict.datetime);
            $item.attr({id: nodeDict.id, username: nodeDict.creator});

            if (nodeDict.parent_id) {
                // 挂在谁下
                $('#' + nodeDict.parent_id).children('.child').append($item);
            } else {
                // 根下
                $('.comment-list').append($item);
            }
        }


        /* 回复 提交*/
        function bindClickSubmitBtn(){
            $('#btnSubmit').click(function(){
                var value = $('#content').val();
                var parent_id = $('#replyUser').attr('parent-id');
                $.ajax({
                    url: "{% url 'web:issues_record' project_id=request.tracer.project.id issue_id=issue_object.id %}",
                    type:'POST', //'POST', page?val=xxx&?val2=bbb
                    headers:{'X-CSRFToken':'{{csrf_token}}'},
                    data:{
                        content:value, 
                        reply:parent_id,
                        reply_type: 2,
                        issues:"{{issue_object.id}}",
                        creator:"{{request.tracer.user.id}}"
                        },
                    dataType:'JSON',
                    success:function(ret){
                        //console.log(ret);
                        if (ret.status){
                            //location.reload();
                            createRecordNode(ret.msg);
                            $('#content').val("");
                            $('#content').next('.error-msg').text("");//找标签位置，加标签
                            $('#replyUser').addClass('hide').removeAttr('parent-id').children('span').text("");

                        }else{

                            $.each(ret.msg,function(key,value){//对arg.msg进行循环
                                console.log(value[0]);
                                //var tag = document.createElement('span');
                                $('#content').next('.error-msg').text(value[0]);//找标签位置，加标签
                            })
                        }
                    }
                })
            })
        }
    
        /* 问题编辑提交*/
        function bindIssueChange(){
            $('.form-control').change(function(){
                $('.error-msg').empty();
                var _postDict = {name: $(this).attr('name'), 
                value: $(this).val()};
                //console.log(_postDict);
                if ($(this).attr('name')) {
                    submitIssueChange(_postDict);
                }
            })
        }

      


        function submitIssueChange(postDict){
            //var nm1=$('input[name="inputname"]').val();
            //var var_nm1 = $.cookie('csrftoken');
            //var id_user = $('#id_user').val();
                $.ajax({
                    url:"{% url 'web:issue_change' project_id=request.tracer.project.id issue_id=issue_object.id%}", //to any url
                    //url: '/csrf1.html',
                    type: 'POST',
                    headers:{
                        'X-CSRFToken':'{{csrf_token}}',
                        "Content-Type": "application/json;charset=utf-8"
                    },
                    data: JSON.stringify(postDict),
                    dataType: 'JSON',
                    success:function(arg){
                        //console.log(arg);
                        if (arg.status){
                            if (arg.msg)
                                {createRecordNode(arg.msg);}
                        }else{
                            $('#id_'+postDict.name).parent().next('.error-msg').text(arg.msg);
                        }
                    }
                })
        }

</script>

{% endblock js %}